package com.share.tool.generator.json2field;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.share.common.constant.DirConstant;
import com.share.common.utils.FileUtil;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 把json的key提取出来，并转换为java的属性，只处理第一层
 */
public class MainJ2F {
    static String filePath = DirConstant.TMP_DIR + File.separator + "json.txt";


    public static void main(String[] args) {
        List<String> reList = new LinkedList<>();

        List<String> daList = FileUtil.readByLine(new File(filePath));
        StringBuffer sb = new StringBuffer();
        for (String str : daList) {
            if (StringUtils.isBlank(str)) {//说明结束了
                int length = sb.length();
                if (length > 2) {
                    String jsonStr = sb.toString();//暂存

                    sb.setLength(0);//清空

                    JSONObject obj = JSON.parseObject(jsonStr);
                    List<String> list = listJSONObject(obj);
                    reList.addAll(list);

                    reList.add("");//一组处理完毕了添加一个换行符
                }
            } else {
                sb.append(str);
            }
        }

        //防止之后的没有换行
        if (sb.length() > 0) {
            JSONObject obj = JSON.parseObject(sb.toString());
            List<String> list = listJSONObject(obj);
            reList.addAll(list);
        }


        for (String str : reList) {
            System.out.println(str);
        }
    }

    //遍历这个json-------只处理第一层
    public static List<String> listJSONObject(JSONObject obj) {
        List<String> list = new LinkedList<>();
        if (obj != null) {
            Set<Map.Entry<String, Object>> entrySet = obj.entrySet();
            for (Map.Entry<String, Object> entry : entrySet) {
                String field = entry.getKey();
//                String camel2under = StrUtil.camel2under(field);

                Object value = entry.getValue();
                String type = "String";
                if (value != null) {
                    String[] typeSplit = value.getClass().getName().split("\\.");
                    type = typeSplit[typeSplit.length - 1];
                }
                String beanField = "private " + type + " " + field + ";";
                list.add(beanField);

                if ("JSONObject".equals(type)) {
                    System.out.println(field + ":");
                    System.out.println(value);
                    System.out.println();
                }
            }
        }
        return list;
    }

}
